﻿#ifndef __BPFPI83__
#define __BPFPI83__
#include <iostream>
/***
*<BPFPI>P89 t2
输入n，求一个n*n 矩阵。规定矩阵沿45°线递增，形成一个zigzag 数组(JPEG编码里取像素数据的排列顺序)
，请问用c++ 如何实现？
*/
class BPFPI83{
 public:
	static void TestDrive(int n){
		//initiallize
	int ** arrs = new int*[n];
	for(int i = 0;i < n; ++i){
		if((arrs[i] = new int[n]) == NULL) {
			while(i >= 0){//when error free the memory
				delete [] arrs[i];
				arrs[i--] = NULL;
			}
			delete [] arrs;
			return ;
		}
	}
	int squa = n * n ;
	for(int i = 0 ; i < n; ++i){
		for(int j = 0 ; j< n; ++j){
			int sum = i+j;
			if(sum < n)// the up side
				arrs[i][j] = sum * (sum + 1)/2 + (((i+j) % 2 == 0) ? i : j);
			else{// down side
				sum = (n-1-i) + (n-1-j);
				arrs[i][j] = squa - sum * (sum + 1)/2 -(n - (((i+j) % 2 == 0) ? i : j));
			}
				
		}
	}
	//output
	for(int i = 0; i < n ; ++i ){
		for(int j = 0 ; j < n ; ++j){
			std::cout << arrs[i][j] << " ";
		}
		std::cout << std::endl;
	}
	// clean work
	for(int i = 0; i < n; ++i){
		delete [] arrs[i];
		arrs[i] = NULL;
	}
	delete [] arrs;
	arrs = NULL;
	}
};
#endif